package edu.cmu.vlis.wassup.sender;

import java.io.IOException;
import java.util.Arrays;

import edu.cmu.vlis.wassup.CoordinatorResponder;

public class MPCoordinatorResponder extends CoordinatorResponder{

	private MessageProcessor mp;

	public MPCoordinatorResponder(int port, MessageProcessor msgProcessor) {
		super(port);
		this.mp = msgProcessor;
	}

	@Override
	public void run(){

		String line;
		while(true){
			try {
				Thread.sleep(2000);
				line = this.reader.readLine(); 
				out1.write("MP rcvd from coordinator:"+line + "\n");
				out1.flush();
				if(line.equals("ALIVE?")){
					this.out.println("Yes");
				}
				else if(line.startsWith("Restart:")){
					String[] parts = line.split(":");
					String[] newUrls = new String[parts.length-1];
					for(int i =1; i<parts.length; i++){
						newUrls[i-1] = parts[i];
						out1.write("i"+i + "\n");
					}
					out1.write("After parts"+line + "\n");
					this.mp.reset(newUrls);
					out1.write("After mp"+line + "\n");
					//this.mp.reset((Arrays.asList(parts)).subList(1, parts.length-1).toArray(new String[0]));

					this.out.println("Yes");
					out1.write("After out"+line + "\n");
					out1.write("Send Yes"+line + "\n");
					out1.flush();
				}
				else {
					this.out.println("");
					this.out.flush();
					out1.write("I am sending empty line.. bec i dont know wht i got.. .\n");
					out1.flush();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}catch (NullPointerException npe){
				try {
					out1.write("It seems connection with coordinator is lost..\n");
					out1.write(npe.toString());
					out1.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				this.initialize();
			}
		}

	}
}
